"""
健康检查和监控端点
"""

import asyncio
import time
from typing import Dict, Any, List
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from ...core.database import get_db
from ...core.config import settings
from ...core.logging import get_logger
from ...core.exceptions import AppException
from ...services.cache import cache_service
from ...tasks.queue_manager import queue_manager
from ...monitoring.performance_monitor import performance_monitor
from ...monitoring.memory_optimizer import memory_optimizer
from ...monitoring.load_balancer import load_balancing_manager
from ...services.tts import tts_service
from ...services.audio import audio_service

logger = get_logger(__name__)
router = APIRouter(prefix="/health", tags=["Health"])


@router.get("/")
async def health_check():
    """基础健康检查"""
    return {
        "status": "healthy",
        "timestamp": time.time(),
        "version": settings.VERSION,
        "service": "offline-language-player"
    }


@router.get("/detailed")
async def detailed_health_check(db: AsyncSession = Depends(get_db)):
    """详细健康检查"""
    health_status = {
        "status": "healthy",
        "timestamp": time.time(),
        "version": settings.VERSION,
        "checks": {}
    }
    
    overall_healthy = True
    
    # 数据库检查
    try:
        await db.execute("SELECT 1")
        health_status["checks"]["database"] = {
            "status": "healthy",
            "response_time": "fast"
        }
    except Exception as e:
        health_status["checks"]["database"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        overall_healthy = False
    
    # 缓存检查
    try:
        await cache_service.ping()
        health_status["checks"]["cache"] = {
            "status": "healthy",
            "response_time": "fast"
        }
    except Exception as e:
        health_status["checks"]["cache"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        overall_healthy = False
    
    # TTS服务检查
    try:
        voices = await tts_service.get_available_voices()
        health_status["checks"]["tts"] = {
            "status": "healthy",
            "available_voices": len(voices)
        }
    except Exception as e:
        health_status["checks"]["tts"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        overall_healthy = False
    
    # 任务队列检查
    try:
        queue_stats = await queue_manager.get_global_statistics()
        health_status["checks"]["task_queue"] = {
            "status": "healthy",
            "active_queues": queue_stats["active_queues"],
            "total_tasks": queue_stats["total_pending_tasks"]
        }
    except Exception as e:
        health_status["checks"]["task_queue"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        overall_healthy = False
    
    # 内存状态检查
    try:
        memory_status = memory_optimizer.get_memory_status()
        memory_report = memory_optimizer.get_optimization_report()
        
        health_status["checks"]["memory"] = {
            "status": "healthy" if memory_status.value in ["healthy", "warning"] else "unhealthy",
            "status_value": memory_status.value,
            "current_memory_mb": memory_report.get("current_memory", {}).get("rss_mb", 0)
        }
        
        if memory_status.value not in ["healthy", "warning"]:
            overall_healthy = False
            
    except Exception as e:
        health_status["checks"]["memory"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        overall_healthy = False
    
    health_status["status"] = "healthy" if overall_healthy else "unhealthy"
    
    # 设置HTTP状态码
    status_code = 200 if overall_healthy else 503
    
    return JSONResponse(
        status_code=status_code,
        content=health_status
    )


@router.get("/ready")
async def readiness_check():
    """就绪检查"""
    try:
        # 检查关键服务是否就绪
        checks = []
        
        # 检查数据库连接
        if hasattr(get_db, '__call__'):
            checks.append(("database", True))
        else:
            checks.append(("database", False))
        
        # 检查TTS服务
        voices = await tts_service.get_available_voices()
        checks.append(("tts", len(voices) > 0))
        
        # 检查缓存
        try:
            await cache_service.ping()
            checks.append(("cache", True))
        except:
            checks.append(("cache", False))
        
        # 检查任务管理器
        try:
            await queue_manager.get_global_statistics()
            checks.append(("task_queue", True))
        except:
            checks.append(("task_queue", False))
        
        # 所有检查通过才算就绪
        ready = all(check[1] for check in checks)
        
        return {
            "ready": ready,
            "checks": {name: status for name, status in checks},
            "timestamp": time.time()
        }
        
    except Exception as e:
        return {
            "ready": False,
            "error": str(e),
            "timestamp": time.time()
        }


@router.get("/live")
async def liveness_check():
    """存活检查"""
    return {
        "alive": True,
        "timestamp": time.time(),
        "uptime": time.time() - getattr(liveness_check, '_start_time', time.time())
    }


# 记录启动时间
liveness_check._start_time = time.time()


@router.get("/metrics")
async def metrics_endpoint():
    """Prometheus格式的指标"""
    try:
        # 获取性能指标
        perf_summary = await performance_monitor.get_performance_summary()
        memory_report = memory_optimizer.get_optimization_report()
        queue_stats = await queue_manager.get_global_statistics()
        
        # 生成Prometheus格式指标
        metrics = []
        
        # 应用指标
        metrics.append(f"# HELP app_uptime_seconds Application uptime in seconds")
        metrics.append(f"# TYPE app_uptime_seconds counter")
        metrics.append(f"app_uptime_seconds {perf_summary['uptime_seconds']}")
        
        metrics.append(f"# HELP app_memory_usage_bytes Memory usage in bytes")
        metrics.append(f"# TYPE app_memory_usage_bytes gauge")
        current_memory = memory_report.get("current_memory", {})
        rss_mb = current_memory.get("rss_mb", 0)
        metrics.append(f"app_memory_usage_bytes {int(rss_mb * 1024 * 1024)}")
        
        metrics.append(f"# HELP app_cpu_usage_percent CPU usage percentage")
        metrics.append(f"# TYPE app_cpu_usage_percent gauge")
        cpu_percent = perf_summary.get("process_metrics", {}).get("cpu_percent", 0)
        metrics.append(f"app_cpu_usage_percent {cpu_percent}")
        
        # 请求指标（如果有）
        metrics.append(f"# HELP http_requests_total Total HTTP requests")
        metrics.append(f"# TYPE http_requests_total counter")
        metrics.append(f"http_requests_total {perf_summary.get('total_requests', 0)}")
        
        # 任务队列指标
        metrics.append(f"# HELP task_queue_pending_tasks Number of pending tasks")
        metrics.append(f"# TYPE task_queue_pending_tasks gauge")
        metrics.append(f"task_queue_pending_tasks {queue_stats.get('total_pending_tasks', 0)}")
        
        metrics.append(f"# HELP task_queue_active_queues Number of active task queues")
        metrics.append(f"# TYPE task_queue_active_queues gauge")
        metrics.append(f"task_queue_active_queues {queue_stats.get('active_queues', 0)}")
        
        # 告警指标
        metrics.append(f"# HELP app_alerts_active Number of active alerts")
        metrics.append(f"# TYPE app_alerts_active gauge")
        active_alerts = perf_summary.get("alerts", {}).get("active_count", 0)
        metrics.append(f"app_alerts_active {active_alerts}")
        
        return "\n".join(metrics)
        
    except Exception as e:
        logger.error(f"Failed to generate metrics: {e}")
        return f"# Error generating metrics: {str(e)}"


@router.get("/status")
async def system_status():
    """系统状态概览"""
    try:
        # 收集各模块状态
        status = {
            "timestamp": time.time(),
            "application": {
                "version": settings.VERSION,
                "environment": settings.ENVIRONMENT,
                "debug": settings.DEBUG
            },
            "services": {}
        }
        
        # 数据库状态
        try:
            # 这里需要获取数据库会话来检查
            status["services"]["database"] = "running"
        except:
            status["services"]["database"] = "error"
        
        # 缓存状态
        try:
            await cache_service.ping()
            status["services"]["cache"] = "running"
        except:
            status["services"]["cache"] = "error"
        
        # TTS服务状态
        try:
            voices = await tts_service.get_available_voices()
            status["services"]["tts"] = {
                "status": "running",
                "voices_count": len(voices)
            }
        except:
            status["services"]["tts"] = "error"
        
        # 音频服务状态
        try:
            # 简单检查音频服务是否可用
            status["services"]["audio"] = "running"
        except:
            status["services"]["audio"] = "error"
        
        # 任务队列状态
        try:
            queue_stats = await queue_manager.get_global_statistics()
            status["services"]["task_queue"] = {
                "status": "running",
                "active_queues": queue_stats["active_queues"],
                "pending_tasks": queue_stats["total_pending_tasks"]
            }
        except:
            status["services"]["task_queue"] = "error"
        
        # 性能监控状态
        try:
            perf_summary = await performance_monitor.get_performance_summary()
            status["services"]["performance_monitor"] = {
                "status": "running",
                "monitoring": perf_summary["monitoring"]["monitoring"]
            }
        except:
            status["services"]["performance_monitor"] = "error"
        
        # 内存优化器状态
        try:
            memory_report = memory_optimizer.get_optimization_report()
            status["services"]["memory_optimizer"] = {
                "status": "running",
                "memory_status": memory_report["memory_status"],
                "optimizations_performed": memory_report["optimization_stats"]["optimizations_performed"]
            }
        except:
            status["services"]["memory_optimizer"] = "error"
        
        # 负载均衡器状态
        try:
            lb_stats = await load_balancing_manager.get_global_stats()
            status["services"]["load_balancer"] = {
                "status": "running",
                "total_balancers": lb_stats["total_balancers"],
                "total_nodes": lb_stats["total_nodes"]
            }
        except:
            status["services"]["load_balancer"] = "error"
        
        # 计算整体状态
        service_statuses = []
        for service, service_info in status["services"].items():
            if isinstance(service_info, dict):
                service_statuses.append(service_info.get("status", "error") == "running")
            else:
                service_statuses.append(service_info == "running")
        
        status["overall_status"] = "healthy" if all(service_statuses) else "degraded"
        
        return status
        
    except Exception as e:
        logger.error(f"Failed to get system status: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to get system status: {str(e)}")


@router.get("/dependencies")
async def dependencies_check():
    """检查外部依赖"""
    dependencies = {
        "timestamp": time.time(),
        "dependencies": {}
    }
    
    # 检查数据库
    try:
        # 尝试数据库连接
        dependencies["dependencies"]["database"] = {
            "status": "available",
            "version": "sqlite"  # 可以通过查询获取实际版本
        }
    except Exception as e:
        dependencies["dependencies"]["database"] = {
            "status": "unavailable",
            "error": str(e)
        }
    
    # 检查Redis（如果配置了）
    if settings.REDIS_URL:
        try:
            await cache_service.ping()
            dependencies["dependencies"]["redis"] = {
                "status": "available",
                "url": settings.REDIS_URL.replace("password", "***")  # 隐藏密码
            }
        except Exception as e:
            dependencies["dependencies"]["redis"] = {
                "status": "unavailable",
                "error": str(e)
            }
    
    # 检查TTS引擎
    try:
        voices = await tts_service.get_available_voices()
        dependencies["dependencies"]["tts_engine"] = {
            "status": "available",
            "engine": "pyttsx3",
            "voices_count": len(voices)
        }
    except Exception as e:
        dependencies["dependencies"]["tts_engine"] = {
            "status": "unavailable",
            "error": str(e)
        }
    
    # 检查音频处理库
    try:
        import pydub
        import soundfile
        
        dependencies["dependencies"]["audio_libraries"] = {
            "status": "available",
            "pydub_version": pydub.__version__ if hasattr(pydub, '__version__') else "unknown",
            "soundfile_version": soundfile.__version__ if hasattr(soundfile, '__version__') else "unknown"
        }
    except ImportError as e:
        dependencies["dependencies"]["audio_libraries"] = {
            "status": "unavailable",
            "error": f"Import error: {str(e)}"
        }
    except Exception as e:
        dependencies["dependencies"]["audio_libraries"] = {
            "status": "error",
            "error": str(e)
        }
    
    # 检查文件系统
    try:
        import os
        # 尝试写入测试文件
        test_file = os.path.join(settings.DATA_DIR, ".health_check")
        with open(test_file, 'w') as f:
            f.write("test")
        os.remove(test_file)
        
        dependencies["dependencies"]["filesystem"] = {
            "status": "available",
            "data_dir": settings.DATA_DIR
        }
    except Exception as e:
        dependencies["dependencies"]["filesystem"] = {
            "status": "unavailable",
            "error": str(e)
        }
    
    return dependencies


@router.get("/performance")
async def performance_summary():
    """性能摘要"""
    try:
        # 获取性能数据
        perf_summary = await performance_monitor.get_performance_summary()
        memory_report = memory_optimizer.get_optimization_report()
        queue_stats = await queue_manager.get_global_statistics()
        
        return {
            "timestamp": time.time(),
            "performance": perf_summary,
            "memory": memory_report,
            "task_queue": queue_stats
        }
        
    except Exception as e:
        logger.error(f"Failed to get performance summary: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to get performance summary: {str(e)}")


@router.post("/test/{test_type}")
async def run_health_test(test_type: str, db: AsyncSession = Depends(get_db)):
    """运行特定健康测试"""
    try:
        if test_type == "database":
            # 测试数据库
            start_time = time.time()
            await db.execute("SELECT 1")
            response_time = (time.time() - start_time) * 1000
            
            return {
                "test": "database",
                "status": "passed",
                "response_time_ms": response_time,
                "timestamp": time.time()
            }
        
        elif test_type == "cache":
            # 测试缓存
            start_time = time.time()
            await cache_service.ping()
            response_time = (time.time() - start_time) * 1000
            
            return {
                "test": "cache",
                "status": "passed",
                "response_time_ms": response_time,
                "timestamp": time.time()
            }
        
        elif test_type == "tts":
            # 测试TTS服务
            start_time = time.time()
            voices = await tts_service.get_available_voices()
            response_time = (time.time() - start_time) * 1000
            
            return {
                "test": "tts",
                "status": "passed",
                "response_time_ms": response_time,
                "voices_count": len(voices),
                "timestamp": time.time()
            }
        
        elif test_type == "audio_processing":
            # 测试音频处理
            start_time = time.time()
            # 这里可以添加实际的音频处理测试
            response_time = (time.time() - start_time) * 1000
            
            return {
                "test": "audio_processing",
                "status": "passed",
                "response_time_ms": response_time,
                "timestamp": time.time()
            }
        
        else:
            raise HTTPException(status_code=404, detail=f"Unknown test type: {test_type}")
            
    except Exception as e:
        logger.error(f"Health test {test_type} failed: {e}")
        return {
            "test": test_type,
            "status": "failed",
            "error": str(e),
            "timestamp": time.time()
        }


@router.get("/logs")
async def get_recent_logs(
    level: str = Query("INFO", description="Log level filter"),
    lines: int = Query(100, description="Number of lines to return")
):
    """获取最近的日志"""
    try:
        # 这里应该从日志文件或日志系统中读取
        # 为了简化，返回一个示例结构
        return {
            "timestamp": time.time(),
            "level": level,
            "lines": lines,
            "logs": [
                {
                    "timestamp": time.time() - 300,
                    "level": "INFO",
                    "message": "Application started successfully",
                    "module": "main"
                },
                {
                    "timestamp": time.time() - 240,
                    "level": "INFO",
                    "message": "Database connection established",
                    "module": "database"
                },
                {
                    "timestamp": time.time() - 180,
                    "level": "WARNING",
                    "message": "High memory usage detected",
                    "module": "memory_optimizer"
                }
            ]
        }
        
    except Exception as e:
        logger.error(f"Failed to get logs: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to get logs: {str(e)}")


@router.get("/config")
async def get_config_info():
    """获取配置信息（仅安全信息）"""
    return {
        "timestamp": time.time(),
        "config": {
            "version": settings.VERSION,
            "environment": settings.ENVIRONMENT,
            "debug": settings.DEBUG,
            "log_level": settings.LOG_LEVEL,
            "data_dir": settings.DATA_DIR,
            "max_file_size": settings.MAX_FILE_SIZE,
            "supported_audio_formats": settings.SUPPORTED_AUDIO_FORMATS,
            "supported_video_formats": settings.SUPPORTED_VIDEO_FORMATS
        }
    }
